import uuid4 from "uuid/v4";
import request from "./request";

function uuid() {
  return uuid4().replace(/-/g, "");
}
class Policy {
  constructor(policy) {
    if (policy.host.endsWith("/")) {
      policy.host = policy.host.substring(0, policy.host.length - 1);
    }
    if (policy.dir !== "" && !policy.dir.endsWith("/")) {
      policy.dir = policy.dir + "/";
    }
    if (!policy.dir.startsWith("/")) {
      policy.dir = "/" + policy.dir;
    }
    this.policy = policy;
  }
  isExpire() {
    return Date.now() / 1000 > this.policy.expire - 3;
  }
  buildFullPath(name) {
    if (name != null && name.startsWith("/")) {
      name = name.substring(1);
    }
    return `${this.policy.host}${this.policy.dir}${name}`;
  }
  get host() {
    return this.policy.host;
  }
  get dir() {
    return this.policy.dir;
  }
  get props() {
    return {
      policy: this.policy.policy,
      OSSAccessKeyId: this.policy.accessId,
      signature: this.policy.signature,
      success_action_status: "200" //让服务端返回200,不然，默认会返回204
    };
  }
}

let currentPolicyInstance = null;

class UploadProps {
  constructor(policy, file) {
    this._policy = policy;
    let ext = "";
    if (file.name.lastIndexOf(".") !== -1) {
      ext = file.name.substring(file.name.lastIndexOf("."));
    }
    this._filename = `${uuid()}${ext}`;
  }
  get host() {
    return this._policy.host;
  }
  get fullPath() {
    return this._policy.buildFullPath(this._filename);
  }
  get props() {
    const path = `${this._policy.dir}${this._filename}`;
    return {
      key: path.substring(1),
      ...this._policy.props
    };
  }
}

function requestUploadPolicy() {
  return request.get("/sys/oss/getUploadPolicy").then(({ data }) => {
    if (data.errors) {
      console.log(data.errors);
      return Promise.reject(new Error("no policy found"));
    } else {
      currentPolicyInstance = new Policy(data.data);
      return currentPolicyInstance;
    }
  });
}

function getOssPolicy() {
  if (currentPolicyInstance && currentPolicyInstance.isExpire()) {
    currentPolicyInstance = null;
  }
  if (currentPolicyInstance) {
    return Promise.resolve(currentPolicyInstance);
  } else {
    return requestUploadPolicy();
  }
}

export function getUploadProps(file) {
  return getOssPolicy().then(policy => {
    return new UploadProps(policy, file);
  });
}
